from ..models import deployInfo
from ..models import deploy_history
from systemd.models import robot_dtalk
from libs.dtalk import Dtalk_Message


class update_log():
    '''将错误信息写入日志文件并更改项目的构建状态通过钉钉消息发送出去'''

    def __init__(self, projectName, clusterName, projectType, status, message, code, *args, **kwargs):
        self.code = code
        self.status = status
        self.message = message
        self.projectName = projectName
        self.projectType = projectType
        self.clusterName = clusterName

    def update_dtalk(self, log_path, log_info):
        '''
        钉钉推送消息
        :param log_path: str
        :param log_info: str
        :return:
        '''

        if self.status is True:
            deployInfo.objects.filter(name=self.projectName,
                                      env=self.clusterName,
                                      application_type=self.projectType).update(status='success')
        else:
            deployInfo.objects.filter(name=self.projectName,
                                      env=self.clusterName,
                                      application_type=self.projectType).update(status='failed')
        # dingTalk msg
        # webHook = robot_dtalk.objects.filter(robot_name='deploy').values().first()
        # Dtalk_Message(project_name=self.projectName,
        #               project_type=self.projectType,
        #               cluster_name=self.clusterName,
        #               webhook=webHook.get('webhook')).protoInfo(deploy_status=self.status,
        #                                                         deploy_message=self.message)
        with open(f"{log_path}/{self.projectName}.log", 'a+') as f:
            f.write(log_info)
        # 存储历史发布日志数据到数据库
        history_log = ""
        with open(f"{log_path}/{self.projectName}.log", encoding="utf-8") as f:
            for log in reversed(f.readlines()):
                history_log += log.strip() + '%,'
        rest_log = deploy_history.objects.create(name=self.projectName,
                                                 logs=str(history_log),
                                                 status=self.status,
                                                 env=self.clusterName,
                                                 application_type=self.projectType)
        rest_log.save()
        return {'code': self.code, 'msg': self.message}
